<template>
  <div class="issue-report-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryForm" ref="queryFormRef" :inline="true" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="古树ID" prop="treeId">
              <el-input v-model.number="queryForm.treeId" placeholder="请输入古树ID" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="处理状态" prop="status">
              <el-select v-model.number="queryForm.status" placeholder="请选择处理状态" clearable style="width: 100%; min-width: 150px">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 修改问题类型选择器 -->
          <el-col :span="6">
            <el-form-item label="问题类型" prop="issueType">
              <el-select v-model="queryForm.issueType" placeholder="请选择问题类型" clearable style="width: 100%; min-width: 150px">
                <el-option v-for="item in issueTypeOptions" :key="item.value" :label="item.label" :value="item.value">

                </el-option>
              </el-select>

            </el-form-item>

          </el-col>


          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 报告列表 -->
    <el-card class="issue-list-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>问题报告列表</span>
          <div>
            <el-button type="danger" size="small" @click="batchDelete"
              :disabled="selectedReports.length === 0">批量删除</el-button>
            <el-button type="primary" size="small" @click="fetchIssueReports">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table :data="issueReports" style="width: 100%" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="treeId" label="古树ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="issueType" label="问题类型" width="120">
          <template #default="scope">
            <el-tag :type="getIssueTypeTag(scope.row.issueType)">
              {{ getIssueTypeName(scope.row.issueType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="问题描述" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.description.substring(0, 50) + (scope.row.description.length > 50 ? '...' : '') }}
          </template>
        </el-table-column>
        <el-table-column prop="contactInfo" label="联系方式" width="120" />
      <el-table-column prop="reportTime" label="提交时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.reportTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row)">查看</el-button>
            <el-button size="small" type="success" @click="handleReport(scope.row)"
              :disabled="[2].includes(scope.row.status)">处理</el-button>
            <el-button size="small" type="danger" @click="deleteReport(scope.row.reportId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[5,10, 20, 50]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange"
        style="margin-top: 20px; justify-content: flex-end;" />
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="问题报告详情" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="报告ID">{{ currentDetail.reportId }}</el-descriptions-item>
        <el-descriptions-item label="古树ID">{{ currentDetail.treeId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.userId }}</el-descriptions-item>
        <el-descriptions-item label="问题类型">{{ getIssueTypeName(currentDetail.issueType) }}</el-descriptions-item>
        <el-descriptions-item label="问题描述">{{ currentDetail.description }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentDetail.contactInfo }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ currentDetail.reportTime }}</el-descriptions-item>
        <el-descriptions-item label="处理状态">{{ getStatusName(currentDetail.status) }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <div v-if="currentDetail.photoUrls && currentDetail.photoUrls.length > 0">
            <el-image v-for="(url, index) in currentDetail.photoUrls" :key="index" :src="url"
              :preview-src-list="currentDetail.photoUrls" :initial-index="index"
              style="width: 100px; height: 100px; margin-right: 10px;" fit="cover" />
          </div>
          <span v-else>无图片</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 处理报告对话框 -->
    <el-dialog v-model="handleDialogVisible" title="处理问题报告" width="500px">
      <el-form :model="handleForm" label-width="100px">
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTag(currentHandleReport.status)">
            {{ getStatusName(currentHandleReport.status) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="更新状态" prop="status">
          <el-select v-model="handleForm.status" placeholder="请选择处理结果">
            <el-option label="已解决" :value="2"></el-option>
            <el-option label="需复查" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input v-model="handleForm.remark" type="textarea" placeholder="请输入处理备注（可选）" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitHandle">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getTreeIssueReportList, deleteTreeIssueReport,setTreeIssueReport }
 from '@/apis/treeAPI'
// 查询表单引用
const queryFormRef = ref()

// 查询表单数据
const queryForm = reactive({
  treeId: null,
  status: null,
  issueType: null
})


// 问题类型选项
const issueTypeOptions = [
  { value: 0, label: '位置信息错误' },
  { value: 1, label: '树木状态变化' },
  { value: 2, label: '基本信息错误' },
  { value: 3, label: '图片问题' },
  { value: 4, label: '其他问题' }
]

// 文件列表
const fileList = ref([])

// 报告列表数据
const issueReports = ref([])
const allIssueReports = ref([]) // 存储所有数据用于筛选
const loading = ref(false)

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentDetail = ref({})

// 处理报告对话框
const handleDialogVisible = ref(false)
const currentHandleReport = ref({})
const handleForm = reactive({
  status: 2,
  remark: ''
})

// 选中的报告
const selectedReports = ref([])

// 获取问题类型标签
const getIssueTypeName = (type) => {
  const option = issueTypeOptions.find(item => item.value === type)
  return option ? option.label : '未知类型'
}

// 获取问题类型标签样式
const getIssueTypeTag = (type) => {
  const types = ['', 'success', 'warning', 'danger', 'info']
  return types[type] || ''
}

// 状态选项
const statusOptions = [
  { value: 0, label: '未处理' },
  { value: 1, label: '处理中' },
  { value: 2, label: '已解决' },
  { value: 3, label: '需复查' }
]

// 获取状态名称
const getStatusName = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '未知状态'
}
// 格式化日期时间
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const types = ['', 'warning', 'success', 'danger']
  return types[status] || ''
}

// 监听查询条件变化，自动触发查询
watch(() => queryForm.status, (newVal) => {
  // 当值发生变化时触发查询（包括清除操作）
  handleQuery()
})

watch(() => queryForm.issueType, (newVal) => {
  // 当值发生变化时触发查询（包括清除操作）
  handleQuery()
})

// 查询处理
const handleQuery = () => {
  // 重置到第一页并应用筛选条件
  pagination.currentPage = 1
  fetchIssueReports()
}
// 重置查询条件
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  // 重置到第一页并重新获取数据
  pagination.currentPage = 1
  fetchIssueReports()
}

// 筛选数据

const filterReports = () => {
  let filtered = [...allIssueReports.value]

  // 根据古树ID筛选
  if (queryForm.treeId !== null && queryForm.treeId !== undefined && queryForm.treeId !== '') {
    filtered = filtered.filter(item => item.treeId === queryForm.treeId)
  }

  // 根据状态筛选 (修改这部分)
  if (queryForm.status !== null && queryForm.status !== undefined && queryForm.status !== '') {
    // 转换为数字进行比较
    filtered = filtered.filter(item => item.status === Number(queryForm.status))
  }

  // 根据问题类型筛选 (修改这部分)
  if (queryForm.issueType !== null && queryForm.issueType !== undefined && queryForm.issueType !== '') {
    // 转换为数字进行比较
    filtered = filtered.filter(item => item.issueType === Number(queryForm.issueType))
  }

  // 更新分页信息
  pagination.total = filtered.length

  // 分页处理
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  issueReports.value = filtered.slice(start, end)
}

// 获取报告列表（从API获取真实数据）
const fetchIssueReports = async () => {
  loading.value = true

  try {
    // 构造查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    if (queryForm.treeId !== null && queryForm.treeId !== undefined && queryForm.treeId !== '') {
      params.treeId = queryForm.treeId
    }

    // 修改状态和问题类型的参数传递逻辑
    if (queryForm.status !== null && queryForm.status !== undefined && queryForm.status !== '') {
      params.status = Number(queryForm.status)  // 转换为数字
    }

    if (queryForm.issueType !== null && queryForm.issueType !== undefined && queryForm.issueType !== '') {
      params.issueType = Number(queryForm.issueType)  // 转换为数字
    }

    // 调用API获取数据
    const response = await getTreeIssueReportList(params)
    if (response && response.data.records) {
      allIssueReports.value = response.data.records
      // 直接调用 filterReports 进行本地筛选和分页
      filterReports()
    } else {
      allIssueReports.value = []
      issueReports.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取问题报告列表失败:', error)
    ElMessage.error('获取问题报告列表失败')
    allIssueReports.value = []
    issueReports.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}


// 查看详情
const viewDetail = (row) => {
  currentDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 处理报告
const handleReport = (row) => {
  currentHandleReport.value = { ...row }
  handleForm.status = 2 // 默认选择已解决
  handleForm.remark = ''
  handleDialogVisible.value = true
}
// 提交处理结果
const submitHandle = async () => {
  try {
    // 调用API更新状态
    const params = {
      reportId: currentHandleReport.value.reportId,
      status: handleForm.status,
      remark: handleForm.remark
    }
    
    const response = await setTreeIssueReport(params)
    
    if (response.code === 1) {
      // 更新成功后更新本地数据
      const index = allIssueReports.value.findIndex(item => item.reportId === currentHandleReport.value.reportId)
      if (index !== -1) {
        allIssueReports.value[index].status = handleForm.status
      }

      // 同时更新当前列表中的数据
      const listIndex = issueReports.value.findIndex(item => item.reportId === currentHandleReport.value.reportId)
      if (listIndex !== -1) {
        issueReports.value[listIndex].status = handleForm.status
      }

      ElMessage.success('处理状态更新成功')
      handleDialogVisible.value = false
      // 重新应用筛选条件
      filterReports()
    } else {
      ElMessage.error(response.msg || '处理状态更新失败')
    }
  } catch (error) {
    console.error('处理状态更新失败:', error)
    ElMessage.error('处理状态更新失败')
  }
}


// 删除报告
const deleteReport = (reportId) => {
  ElMessageBox.confirm('确定要删除这个报告吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      // 调用API删除单个报告
      const result= await deleteTreeIssueReport([reportId]) // 将单个ID包装成数组
      // 从所有数据中删除
      allIssueReports.value = allIssueReports.value.filter(item => item.reportId !== reportId)
      
      if(result.code===1){
       ElMessage.success('删除成功')
       // 重新应用筛选
      filterReports()
      }else{
        ElMessage.warning(result.msg)
      }
     
    } catch (error) {
      console.error('删除报告失败:', error)
      ElMessage.error('删除报告失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请先选择要删除的报告')
    return
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedReports.value.length} 个报告吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 批量删除操作
      const selectedIds = selectedReports.value.map(item => item.reportId)
      const result = await deleteTreeIssueReport(selectedIds) // 调用API批量删除
      allIssueReports.value = allIssueReports.value.filter(item => !selectedIds.includes(item.reportId))
      
     
      if (result.code === 1) { 
        // 重新应用筛选
        ElMessage.success('批量删除成功')
        filterReports()
      } else {
        ElMessage.warning(result.msg)
        fetchIssueReports()
      }

    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 处理选中项变化
const handleSelectionChange = (selection) => {
  selectedReports.value = selection
}

// 分页相关方法
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 重新获取数据
  filterReports()  // 使用本地筛选而不是重新请求API
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  // 重新获取数据
  filterReports()  // 使用本地筛选而不是重新请求API
}

// 组件挂载时获取数据
onMounted(() => {
  fetchIssueReports()
})
</script>

<style scoped>
.status-option,
.issue-type-option {
  display: flex;
  align-items: center;
}

.status-option .el-tag,
.issue-type-option .el-tag {
  margin-right: 8px;
}

.issue-report-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.search-card,
.issue-report-card,
.issue-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.issue-form {
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 添加样式确保选择器文本可见 */
</style>